package cn.zxw.mina;

import cn.zxw.common.TraySystem;
import cn.zxw.login.LoginApp;
import cn.zxw.login.LoginController;
import cn.zxw.login.entity.BaseEntity;
import cn.zxw.messagelist.MessageListApp;
import cn.zxw.prompt.PromptApp;
import cn.zxw.utils.CommenUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.input.MouseEvent;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 功能描述: 消息处理器<br>
 * @Author: zxw
 * @Date: 2020/6/24 10:04
 */
public class ClientHandler extends IoHandlerAdapter {
    public static String token ;
    public static String userName ;
    public static JSONArray listData;
    public static Map<String, String> p_map;
    private ChatClientSupport client;
    public  static Stage messageStage ;
    public static boolean msgNeedFlash = false;
    public  Stage popStage = null;
    public static double x1;
    public static double y1;
    public static double x_stage;
    public static double y_stage;
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        /*System.out.println("exceptionCaught：" + "客户端连接出现异常");*/
    }

    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {

        try {
            String msg = (String)message;
            System.out.println("客户端接收到数据：" + msg);
            /*JSONArray arry = JSON.parseArray(msg);
            JSONObject json = JSON.parseObject(arry.get(0).toString());*/
            JSONObject json = JSONObject.parseObject(msg);
            Object code = json.get("code");

            if(code.equals("101")||code.equals("200")){//登录或者心跳成功
                token=(String)json.get("token");
                userName=(String)json.get("userName");
                if(code.equals("101")){
                    Stage stage = LoginApp.stage;
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run()  {
                            Scene scene = null;
                            try {
                                scene = new Scene(FXMLLoader.load(getClass().getResource("/main/FXML_MAIN.fxml")));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            stage.setScene(scene);
                            scene.setOnMouseDragged(new EventHandler<MouseEvent>() {
                                @Override public void handle(MouseEvent m) {
                                    stage.setX(x_stage + m.getScreenX() - x1);
                                    stage.setY(y_stage + m.getScreenY() - y1);
                                }
                            });
                            scene.setOnDragEntered(null);
                            scene.setOnMousePressed(new EventHandler<MouseEvent>() {
                                @Override public void handle(MouseEvent m) {
                                    //按下鼠标后，记录当前鼠标的坐标
                                    x1 =m.getScreenX();
                                    y1 =m.getScreenY();
                                    x_stage = stage.getX();
                                    y_stage = stage.getY();
                                }
                            });
                            Thread thread = new Thread(() -> {//登录成功4秒消失
                                try {
                                    Thread.sleep(4000);
                                    if (stage.isShowing()) {
                                        Platform.runLater(new Runnable() {
                                            @Override
                                            public void run()  {
                                                if(!TraySystem.min_status){
                                                    TraySystem.getInstance().enableTray(stage);
                                                }
                                                stage.setIconified(true);
                                            }
                                        });
                                    }
                                } catch (Exception exp) {
                                    exp.printStackTrace();
                                }
                            });
                            thread.setDaemon(true);
                            thread.start();
                        }
                    });
                }
                Thread hearThread = new Thread(() -> {
                    try {
                        Thread.sleep(15000);
                        BaseEntity baseEntity = new BaseEntity();
                        baseEntity.setSign("heap");
                        baseEntity.setToken(token);
                        String jsonStr = JSON.toJSONString(baseEntity);
                        session.write(jsonStr); // 用于写入数据并发送*/
                    } catch (Exception exp) {
                        exp.printStackTrace();
                    }
                });
                hearThread.setDaemon(true);
                hearThread.start();
            }else if(code.equals("102")){
                showalertInfo("用户名或者密码错误，请重新尝试");
                session.closeNow();
            }else if(code.equals("500")){
                showalertInfo("未知错误，请重新尝试");
                session.closeNow();
            }else if(code.equals("405")){
                showalertInfo("异常退出，请重新登录");
                session.closeNow();
            }else if(code.equals("403")){
                showalertInfo("该账号已登录，请勿重复登录");
                session.closeNow();
            }else if(code.equals("103")){
                showalertInfo("退出成功！");
                session.closeNow();
            }else if(code.equals("106")){//列表
                String data = json.get("data").toString();
                if(data!=null){
                    listData = JSONArray.parseArray(data);
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run()  {
                            MessageListApp messageListApp = new MessageListApp();
                            try {
                                Scene m_scene = new Scene(FXMLLoader.load(getClass().getResource("/messagelist/list.fxml")));
                                try {
                                    messageStage = messageListApp.start();
                                    messageStage.setScene(m_scene);
                                    m_scene.setOnMouseDragged(new EventHandler<MouseEvent>() {
                                        @Override public void handle(MouseEvent m) {
                                            messageStage.setX(x_stage + m.getScreenX() - x1);
                                            messageStage.setY(y_stage + m.getScreenY() - y1);
                                        }
                                    });
                                    m_scene.setOnDragEntered(null);
                                    m_scene.setOnMousePressed(new EventHandler<MouseEvent>() {
                                        @Override public void handle(MouseEvent m) {
                                            //按下鼠标后，记录当前鼠标的坐标
                                            x1 =m.getScreenX();
                                            y1 =m.getScreenY();
                                            x_stage = messageStage.getX();
                                            y_stage = messageStage.getY();
                                        }
                                    });
                                    //鼠标离开
                                    m_scene.setOnMouseExited(new EventHandler<MouseEvent>() {
                                        @Override public void handle(MouseEvent m) {
                                            messageStage.hide();
                                        }
                                    });
                                    messageStage.show();
                                    //如果鼠标没有进入窗体--让其五秒自动消失
                                  /*  Thread thread = new Thread(() -> {
                                        try {
                                            Thread.sleep(5000);
                                            Platform.runLater(() -> messageStage.close());
                                        } catch (Exception exp) {
                                            exp.printStackTrace();
                                        }
                                    });
                                    thread.setDaemon(true);
                                    thread.start();*/
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }else if(code.equals("105")){//通知通告
                String type = (String)json.get("type");
                String sendUserOrg = (String)json.get("sendUserOrg");
                String title = (String)json.get("title");
                String id = (String)json.get("id");
                String url = (String)json.get("url");
                Platform.runLater(new Runnable() {
                    @Override
                    public void run()  {
                        //showPop(type,title,sendUserOrg);
                        p_map = new HashMap<>();
                        p_map.put("type",type);
                        p_map.put("title",title);
                        p_map.put("sendUserOrg",sendUserOrg);
                        p_map.put("id",id);
                        p_map.put("url",url);
                        PromptApp promptApp = new PromptApp();
                        try {
                            Scene P_scene = new Scene(FXMLLoader.load(getClass().getResource("/prompt/prompt.fxml")));
                            try {
                                popStage = promptApp.start();
                                popStage.setScene(P_scene);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Properties properties = CommenUtils.getProperties("setting.properties");
                        if(properties!=null){
                            String areatR =(String)properties.get("areatR");
                            String soundR =(String)properties.get("soundR");
                            String taskR =(String)properties.get("taskR");
                            if(!areatR.equals("1")){
                                popStage.show();//弹框提示
                            }
                            if(!taskR.equals("1")){
                                msgNeedFlash=true;//收到消失闪动
                                new TraySystem().Flash();
                            }
                            if(!soundR.equals("1")){
                                playAudio();//播放音频
                            }
                        }else {
                            popStage.show();//弹框提示
                            msgNeedFlash=true;//收到消失闪动
                            new TraySystem().Flash();
                            playAudio();//播放音频
                        }
                    }
                });
                 Thread thread = new Thread(() -> {
                    try {
                        Thread.sleep(5000);
                        if (popStage.isShowing()) {
                            Platform.runLater(() -> popStage.close());
                        }
                    } catch (Exception exp) {
                        exp.printStackTrace();
                    }
                 });
                 thread.setDaemon(true);
                 thread.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        System.out.println("messageSent：" + "客户端发送数据");
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        System.out.println("sessionClosed：" + "客户端session关闭");
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        System.out.println("sessionCreated：" + "客户端创建Session");
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {
        System.out.println("sessionIdle：" + "客户端处于多长时间是空闲状态");
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        System.out.println("sessionOpened：" + "客户端打开Session用于读写数据");
    }

    public void showalertInfo(String msg){
        Platform.runLater(new Runnable() {
            @Override
            public void run()  {
                new Alert(Alert.AlertType.NONE, msg, new ButtonType[]{ButtonType.CLOSE}).show();
            }
        });
    }

    //默认弹框---暂时未使用
    public void showPop(String type,String title,String user){
        Platform.runLater(new Runnable() {
            @Override
            public void run()  {
                //commenUtils.showTimedDialog(type,title,user);
                // instance.showTimedDialog(type,title,user);

            }
        });
    }


    //播放音频
    public void playAudio(){
        Platform.runLater(new Runnable() {
            @Override
            public void run()  {
                String s2 = ClientHandler.class.getResource("yp.mp3").toString();
                Media media1 = new Media(s2);
                MediaPlayer mp1 = new MediaPlayer(media1);
                mp1.play(); //播放
            }
        });
    }
}